package com.kvn.instrument.premain;

import java.io.IOException;
import java.io.InputStream;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

/**
 * @author wzy
 * @date 2017年9月20日 上午10:28:10
 */
public class Transformer implements ClassFileTransformer {
	public static final String classNumberReturns2 = "TransClass.class.2";

	@Override
	public byte[] transform(ClassLoader l, String className, Class<?> c, ProtectionDomain pd, byte[] b) throws IllegalClassFormatException {
		if (!className.equals("com/kvn/instrument/premain/TransClass")) {
			return null;
		}
		return getBytesFromFile(classNumberReturns2);
	}
	
	
	private static byte[] getBytesFromFile(String fileName) {
		try {
			// precondition
			InputStream is = Transformer.class.getResourceAsStream(fileName);
			long length = is.available();
			byte[] bytes = new byte[(int) length];

			// Read in the bytes
			int offset = 0;
			int numRead = 0;
			while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
				offset += numRead;
			}

			if (offset < bytes.length) {
				throw new IOException("Could not completely read file " + fileName);
			}
			is.close();
			return bytes;
		} catch (Exception e) {
			e.printStackTrace();
//			System.out.println("error occurs in _ClassTransformer!" + e.getClass().getName());
			return null;
		}
	}
}
